/***********************************************************************
** Copyright (C) 2011 Anthony Naddeo <anthony.naddeo@gmail.com>
**
** This file is part of scenic
**
** scenic is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** scenic is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this package; If not, see <http://www.gnu.org/licenses/>.
**
***********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <dirent.h>

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void gconf(string imageFile){
	string exec = "gconftool-2 --type=string -s /desktop/meego/background/portrait/picture_filename ";
	//string exec = "gconftool-2 --type=string -s /desktop/gnome/background/picture_filename ";
	exec += imageFile;
	cout << "\n"  << exec << endl;
	system(exec.c_str());
}

void update(string wallpaperDir){
	// get the current hour of the day and
	// store it in 'hour'
	time_t currentTime = time(NULL);
	struct tm *loc = localtime(&currentTime);
	int hour = loc->tm_hour;
	
	// append wallpaper.conf to the directory
	string wallpaperFile = wallpaperDir;
	if(wallpaperDir.at(wallpaperDir.length()-1) == '/'){
		wallpaperFile += "wallpaper.conf";
	}else{
		wallpaperFile += "/wallpaper.conf";
		wallpaperDir += "/";
	}
	
	
	ifstream settings;
	settings.open(wallpaperFile.c_str());
	string line, image;
	int eqIndex, wallpaperHour;
	
	while(getline(settings,line)){
		eqIndex = line.find('=');
		if(eqIndex > 0){
			wallpaperHour = atoi(line.substr(0,eqIndex).c_str());
			if(hour >= wallpaperHour){
				image = line.substr(eqIndex+1,string::npos);
			}
		}	
		
	}
	wallpaperDir += image;
	gconf(wallpaperDir);
	settings.close();
	
	
		// go through the wallpaper.conf file line by line
		// comparing current time to the hour in the file

		// use gconf to set the wallpaper
}

void updateRandom(string wallpaperDir){
	srand(time(NULL));
	cout << "\n\nfinding images" << endl;

	DIR *dir;
	dir = opendir(wallpaperDir.c_str());
	struct dirent *dirStruct;
	
	//append trailing /
	if(wallpaperDir.at(wallpaperDir.length()-1) != '/'){
		wallpaperDir += "/";
	}
	cout << "looking in: " << wallpaperDir << endl;
	
	if(dir){
		cout << "starting main loop" << endl;
		// first loop to see how many images are present
		int numImages = 0;
		while ((dirStruct = readdir (dir)) != NULL) {
			if(dirStruct->d_name[0] != '.' && string(dirStruct->d_name) != "wallpaper.conf" && string(dirStruct->d_name) != "scenic.conf"){
				numImages++;
				cout << "found: " << dirStruct->d_name << endl;
			}
		}
		cout << "total: " << numImages << endl;
		
		closedir(dir);
		dir = opendir(wallpaperDir.c_str());
		
		int randomNum = (rand() % numImages);
		cout << "picking "<< rand()  << " " << randomNum << " randomly" << endl;
		numImages = 0;
		while ((dirStruct = readdir (dir)) != NULL) {
			if(dirStruct->d_name[0] != '.' && string(dirStruct->d_name) != "wallpaper.conf" && string(dirStruct->d_name) != "scenic.conf"){
				if(numImages == randomNum){
					wallpaperDir += string(dirStruct->d_name);
					cout << "\nImage file to use: " << wallpaperDir << endl;
					gconf(wallpaperDir);
					break;
				}else{
					numImages++;
				}
				
			}
		}	
		  closedir(dir);
	}
}

/**
Daemon mode if there are no arguments.
Any arguments will cause it to execute once.
*/
int main(int argc, char *argv[]) {

	do{
		// variables from scenic.conf file
		// to be filled in
	        int interval = 120;                      	//update interval for sleep()
		string wallpaper="/opt/scenic/wallpaper";	//location of wallpaper dir
		string mode="Hourly";		                //Random or Hourly
		string enabled="false";          		//true or false
		
		cout << "opening scenic.conf file" << endl;
	
		ifstream settings;
		settings.open("/home/user/.config/scenic/scenic.conf");
		
		cout << "opened " << endl;

		string line;
		while(getline(settings,line)){
			
			int eqIndex = line.find('=');
		
			if(eqIndex > 0){
				string key = line.substr(0,eqIndex);
				cout << "reading " << key << endl;
			
				if(key == "mode"){
					mode = line.substr(eqIndex+1,string::npos);
				}else if(key == "enabled"){
					enabled = line.substr(eqIndex+1,string::npos);
				}else if(key == "wallpaper"){
					wallpaper = line.substr(eqIndex+1,string::npos);
				}else if(key == "interval"){
					interval = atoi(line.substr(eqIndex+1,string::npos).c_str())*60;
				}	
			}	
		}
		
		cout << "\nFound the following:" << endl;
		cout << "mode: " << mode << endl;
		cout << "enabled: " << enabled << endl;
		cout << "wallpaper dir: " << wallpaper << endl;
		cout << "interval: " << interval << endl;
	
		settings.close();
		
		
		//call the appropriate update algorithm
		if(enabled == "true" && mode == "Hourly"){
			cout << "updating wallpaper" << endl;
			update(wallpaper);
		}else if(enabled == "true" && mode == "Random"){
			cout << "updating wallpaper randomly" << endl;
			updateRandom(wallpaper);
		}
	
		cout << "sleeping for " << ((argc-1) ? 0 : interval) << " seconds" << endl;
		
		sleep( (argc-1) ? 0 : interval);
		
	}while(!(argc-1));	
	
	

	return 0;
}

